<template>
  <el-dialog
    v-dialogDrag
    :class="title === '编辑' ? 'elDialog' : ''"
    :visible.sync="dialogVisible"
    :title="title"
    width="850px"
    @close="resetForm('ruleForm')"
  >
    <button-group
      ref="buttonGroup"
      @deleteCancel="deleteCancel"
      @submitForm="submitForm('ruleForm')"
      @cancel="dialogVisible = false"
    />
    <div class="formTopFont">采购收货单</div>
    <el-row>
      <el-form
        ref="ruleForm"
        :model="ruleForm"
        :rules="rules"
        label-width="100px"
      >
        <el-tabs type="card" tab-position="top">
          <el-tab-pane label="基本信息">
            <el-row>
              <el-col :span="12">
                <el-form-item label="收货单号" prop="receiptNo">
                  <el-input
                    v-model="ruleForm.receiptNo"
                    maxlength="20"
                    show-word-limit
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="供方名称" prop="supplierName">
                  <el-input v-model="ruleForm.supplierName" disabled />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="物料" prop="orderMaterialId">
                  <el-select
                    v-model="ruleForm.orderMaterialId"
                    style="width: 100%"
                    @change="
                      () => {
                        const { unit, num, supplierName, supplierId, isCheck } =
                          materialList.find(
                            (el) =>
                              el.orderMaterialId === ruleForm.orderMaterialId
                          );
                        ruleForm.unit = unit;
                        ruleForm.num = num;
                        ruleForm.supplierName = supplierName;
                        ruleForm.supplierId = supplierId;
                        ruleForm.receivedNum = num;
                        ruleForm.isCheck = isCheck === 1 ? true : false;
                      }
                    "
                  >
                    <el-option
                      v-for="item in materialList"
                      :key="item.orderMaterialId"
                      :label="`${item.materialName}`"
                      :value="item.orderMaterialId"
                    >
                      <span style="float: left">{{ item.materialName }}</span>
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="单位" prop="unit">
                  <el-input v-model="ruleForm.unit" disabled />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="订单数量" prop="num">
                  <el-input-number
                    v-model="ruleForm.num"
                    style="width: 100%"
                    disabled
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="收货日期" prop="receiptDate">
                  <el-date-picker
                    v-model="ruleForm.receiptDate"
                    type="date"
                    placeholder="选择日期时间"
                    style="width: 100%"
                    format="yyyy-MM-dd"
                    value-format="yyyy-MM-dd"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="收货人" prop="userId">
                  <el-select v-model="ruleForm.userId" style="width: 100%">
                    <el-option
                      v-for="item in userAllList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="已收数量" prop="receivedNum">
                  <el-input-number
                    v-model="ruleForm.receivedNum"
                    style="width: 100%"
                    :precision="0"
                    :min="1"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="供方批号" prop="supplierLotNo">
                  <el-input
                    v-model="ruleForm.supplierLotNo"
                    maxlength="20"
                    show-word-limit
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label prop="supplierLotNo">
                  <el-checkbox v-model="ruleForm.isCheck" disabled
                    >检验</el-checkbox
                  >
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="备注" prop="remark">
                  <el-input
                    v-model="ruleForm.remark"
                    maxlength="200"
                    type="textarea"
                    rows="3"
                    show-word-limit
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="入库信息" :disabled="ruleForm.isCheck === true">
            <el-row>
              <el-col :span="12">
                <el-form-item label="库房名称" prop="wmsId">
                  <tree-select
                    :disabled="title === '编辑'"
                    ref="treeSelect"
                    style="width: 100%"
                    :props="{
                      value: 'id',
                      label: 'wmsName',
                      children: 'children',
                    }"
                    :options="wmsListAll"
                    :accordion="true"
                    :value="ruleForm.wmsId"
                    search-key="wmsName"
                    @getNode="getValue($event)"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="入库单号" prop="inNo">
                  <el-input
                    v-model="ruleForm.inNo"
                    :disabled="title === '编辑'"
                    maxlength="20"
                    show-word-limit
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="入库批号" prop="inBatch">
                  <el-input
                    v-model="ruleForm.inBatch"
                    :disabled="title === '编辑'"
                    maxlength="20"
                    show-word-limit
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="入库人" prop="inUserId">
                  <el-select
                    v-model="ruleForm.inUserId"
                    :disabled="title === '编辑'"
                    style="width: 100%"
                  >
                    <el-option
                      v-for="item in userAllList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-col :span="24">
              <el-form-item label="备注" prop="inRemark">
                <el-input
                  v-model="ruleForm.inRemark"
                  :disabled="title === '编辑'"
                  maxlength="200"
                  type="textarea"
                  rows="3"
                  show-word-limit
                />
              </el-form-item>
            </el-col>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-row>
    <bottom-font
      v-if="title === '编辑'"
      ref="bottomFont"
      :obj-name="ruleForm.userName"
      :rew-name="ruleForm.reviewer"
      :obj-date="ruleForm.receiptDate"
    />
  </el-dialog>
</template>
<script>
import TreeSelect from "@/components/TreeSelect";
import { timeFormatToString } from "@/utils/function";
import bottomFont from "@/components/BottomFont";
export default {
  components: { TreeSelect, bottomFont },
  props: {
    userAllList: {
      type: Array,
      default: () => {
        return {};
      },
    },
    supplierAllList: {
      type: Array,
      default: () => {
        return {};
      },
    },
    wmsListAll: {
      type: Array,
      default: () => {
        return [];
      },
    },
  },
  data() {
    const checkReceiptNo = async (rule, value, callback) => {
      const res = await this.$axios.get(
        `/purchase/receipt/verifyNoUnique?no=${value}&id=${
          this.ruleForm.id || ""
        }`
      );
      if (res?.data.code === 200) {
        return res.data.data
          ? callback()
          : new Error(callback("收货单号重复！"));
      } else {
        return new Error(callback(res.data.msg));
      }
    };
    return {
      materialList: [],
      title: "",
      ruleForm: {
        supplierLotNo: "",
        wmsId: "",
        inBatch: "",
        inNo: "",
        inRemark: "",
        inUserId: "",
        supplierId: "", // 供方名称
        receiptNo: "", // 收货单号
        orderMaterialId: "",
        receivedNum: "", // 已收数量
        userId: "", // 收货人主键
        status: "是", // 是否到货(是或否)
        receiptDate: timeFormatToString(new Date()).slice(0, 10), // 收货日期
        remark: "", // 描述
        purchaseNo: "", // 采购单号
      },
      rules: {
        receiptNo: [
          { required: true, message: "收货单号不能为空！", trigger: "blur" },
          { validator: checkReceiptNo, trigger: "blur" },
        ],
        orderMaterialId: [
          { required: true, message: "物料不能为空！", trigger: "change" },
        ],
        receivedNum: [
          { required: true, message: "收货数量不能为空！", trigger: "blur" },
        ],
        receiptDate: [
          { required: true, message: "请选择收货日期", trigger: "change" },
        ],
      },
      dialogVisible: false,
      obj: {},
    };
  },
  watch: {},
  mounted() {},
  methods: {
    /**
     * @description: 新增编辑
     * @param {*} row
     * @return {*}
     */
    async showDialog(row) {
      this.obj = row;
      this.getMaterialAll(row.orderMaterialId);
      if (row && row.hasOwnProperty("id")) {
        const res = await this.$axios.get(
          `/purchase/receipt/detail?id=${row.id}`
        );
        if (res.data.code === 200) {
          this.title = "编辑";
          this.ruleForm = Object.assign({}, res.data.data);
          this.ruleForm.isCheck = this.ruleForm.isCheck === 1 ? true : false;
        }
      } else {
        this.title = "新增";
      }
      this.dialogVisible = true;
    },
    /* 获取所有物料 */
    async getMaterialAll(id) {
      const res = await this.$axios.get(
        `/purchase/receipt/search?orderMaterialId=${id || ""}`
      );
      if (res?.data.code === 200) {
        this.materialList = res.data.data;
      }
    },
    getValue(value) {
      if (value) {
        this.ruleForm.wmsId = value.id;
      } else {
        this.ruleForm.wmsId = "";
      }
    },
    /**
     * @description: 表单提交
     * @param {*} formName
     * @return {*}
     */
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          let url = "";
          if (this.title === "新增") {
            url = "/purchase/receipt/save";
          } else {
            url = "/purchase/receipt/update";
          }
          const res = await this.$axios.post(url, this.ruleForm);
          if (res?.data.code === 200) {
            this.$notify.success("提交成功！");
            this.dialogVisible = false;
            this.$emit("getTableInfo");
          } else {
            this.$notify.error(res.data.msg);
          }
        }
      });
    },
    async deleteCancel() {
      this.$confirm(`确认删除数据？`, "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$axios
            .delete(`/purchase/receipt/remove/${this.obj.id}`)
            .then((res) => {
              if (res.data.code === 200) {
                this.$notify.success("删除成功！");
                this.dialogVisible = false;
                this.$emit("getTableInfo", 1);
              } else {
                this.$notify.error(res.data.msg);
              }
            });
        })
        .catch(() => {});
    },
    /**
     * @description: 重置表单
     * @param {*} formName
     * @return {*}
     */
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.ruleForm = Object.assign({}, this.$options.data.call(this).ruleForm);
    },
  },
};
</script>
<style lang="scss" scoped></style>
